package com.evan.webadmin.biz.controller;


import com.evan.common.core.annotation.MyRequestBody;
import com.evan.common.core.annotation.NoAuthInterface;
import com.evan.common.core.constant.BizConstant;
import com.evan.common.core.object.MyPageData;
import com.evan.common.core.object.MyPageParam;
import com.evan.common.core.object.ResponseResult;
import com.evan.common.core.util.MyModelUtil;
import com.evan.common.core.util.MyPageUtil;
import com.evan.webadmin.biz.dto.SubjectEditDto;
import com.evan.webadmin.biz.dto.SubjectFilter;
import com.evan.webadmin.biz.helper.DictHelper;
import com.evan.webadmin.biz.model.Subject;
import com.evan.webadmin.biz.service.ISubjectService;
import com.evan.webadmin.biz.vo.EvluateSurveyVO;
import com.evan.webadmin.biz.vo.ExamPaperFrontVO;
import com.evan.webadmin.biz.vo.SubjectFrontVo;
import com.evan.webadmin.biz.vo.SubjectVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Pavel
 * @since 2024-06-09
 */
@RestController
@RequestMapping("/admin/biz/subject")
@Slf4j
public class  SubjectController {

    @Autowired
    ISubjectService subjectService;
    @Autowired
    DictHelper dictHelper;

    //题目列表 根据人员类型 题目类型 模块类型 题目名称搜素
    @PostMapping("/findByCondition")
    public ResponseResult<MyPageData<SubjectVo>> findByCondition(@MyRequestBody SubjectFilter subjectFilter,
                                                             @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        List<Subject> subjects = subjectService.findByCondition(subjectFilter.getPersonnelType(), subjectFilter.getModuleType(), subjectFilter.getSubjectType(), subjectFilter.getSceneType(), subjectFilter.getSubjectTitle(), subjectFilter.getSubjectLevel());
        long totalCount = 0L;
        if (subjects instanceof Page) {
            totalCount = ((Page<Subject>) subjects).getTotal();
        }
        List<SubjectVo> subjectVos = MyModelUtil.copyCollectionTo(subjects, SubjectVo.class);
        subjectVos.forEach(i-> {
            i.setSubject(dictHelper.getDictMap(BizConstant.DICTTYPE_SUBJECT_CODE).get(i.getSubjectType() + ""));
            i.setModule(dictHelper.getDictMap(BizConstant.DICTTYPE_MODULE_CODE).get(i.getModuleType() + ""));
            i.setScene(dictHelper.getDictMap(BizConstant.DICTTYPE_SCENE_CODE).get(i.getSceneType() + ""));
            i.setPersonnel(dictHelper.getDictMap(BizConstant.DICTTYPE_PERSONNEL_CODE).get(i.getPersonnelType() + ""));
            i.setLevel(dictHelper.getDictMap(BizConstant.DICTTYPE_SUBJECT_LEVEL_CODE).get(i.getSubjectLevel() + ""));
        });
        return ResponseResult.success(MyPageUtil.makeResponseData(subjectVos, totalCount));
    }

    //题目编辑保存
    @PostMapping("/edit")
    public ResponseResult edit(@RequestBody SubjectEditDto subjectEditDto) {
        subjectService.edit(subjectEditDto);
        return ResponseResult.success();
    }

    //题目删除
    @PostMapping("/delete/{subjectId}")
    public ResponseResult delete(@PathVariable Long subjectId) {
        subjectService.delete(subjectId);
        return ResponseResult.success();
    }

    @GetMapping("/findById")
    public ResponseResult<Subject> findById(@RequestParam String subjectId) {
        return ResponseResult.success(subjectService.findById(Long.valueOf(subjectId)));
    }

    @NoAuthInterface
    @PostMapping("/template/download")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "inline; filename=subject_template.xlsx");
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:/subject_template.xlsx");

            try (InputStream videoFileStream = resource.getInputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = videoFileStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                response.flushBuffer();
            }
        } catch (IOException e) {
            log.error("Error occurred while streaming user /template/download：", e);
        }
    }

    @PostMapping("/import")
    public ResponseResult importData (@RequestParam("file") MultipartFile file,
                                      @RequestParam("personnelType") Integer personnelType,
                                      @RequestParam("moduleType") Integer moduleType) {

        return subjectService.importData(file, personnelType, moduleType);
    }

    @PostMapping("/findByFront")
    public ResponseResult<ExamPaperFrontVO> findByFront(@MyRequestBody SubjectFilter subjectFilter){
        return ResponseResult.success(subjectService.findByFront(subjectFilter));
    }

    @PostMapping("/findByPage")
    public ResponseResult<MyPageData<SubjectFrontVo>> findByPage(@MyRequestBody SubjectFilter subjectFilter,
                                                                      @MyRequestBody MyPageParam pageParam){
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        }
        List<Subject> list = subjectService.findPageByFront(subjectFilter);
        long totalCount = 0L;
        if (list instanceof Page) {
            totalCount = ((Page<Subject>) list).getTotal();
        }
        List<SubjectFrontVo> vos = subjectService.assemblyFront(list);
        return ResponseResult.success(MyPageUtil.makeResponseData(vos, totalCount));
    }

    @PostMapping("/findSurveyByFront")
    public ResponseResult<EvluateSurveyVO> findSurveyByFront(@MyRequestBody SubjectFilter subjectFilter){
        return ResponseResult.success(subjectService.findSurveyByFront(subjectFilter));
    }

    @PostMapping("/logic/delete")
    public ResponseResult logicDelete(@MyRequestBody SubjectFilter subjectFilter) {
        subjectService.logicDelete(subjectFilter.getSubjectId(), subjectFilter.getModuleType());
        return ResponseResult.success();
    }
}

